<?php


namespace app\api\model\user;

use app\common\model\user\LotteryLog as LotteryLogModel;

class LotteryLog extends LotteryLogModel
{
    /**
     * 获取用户今天抽奖
     */
    public static function getUserTodayLottery($user_id, $lottery_id)
    {
        return self::where('user_id', $user_id)->where('lottery_id', $lottery_id)->whereTime('create_time', 'today')->find();
    }

    /**
     * 获取用户今天的抽奖次数
     */
    public static function getUserTodayLotteryCount($user_id, $lottery_id)
    {
        $user_lottery = self::getUserTodayLottery($user_id, $lottery_id);
        return  $user_lottery ? $user_lottery->num : 0;
    }

    /**
     * 获取用户总的抽奖次数
     */
    public static function getUserAllLotteriesCount($user_id, $lottery_id)
    {
        return self::where('user_id', $user_id)->where('lottery_id', $lottery_id)->sum('num');
    }

    /**
     * 添加
     */
    public static function addLog($user_id, $lottery_id)
    {
        return self::create([
            'user_id' => $user_id,
            'lottery_id' => $lottery_id,
            'wxapp_id' => static::$wxapp_id,
            'num' => 1
        ]);
    }

    /**
     * 用户的剩余可抽奖次数
     */
    public static function lastLotteryCount($user_id, $lottery)
    {
        $user_count = 0;
        //每天N次
        if ($lottery->way == 1) {
            $user_count = self::getUserTodayLotteryCount($user_id, $lottery->id);
        }
        //每人N次
        if ($lottery->way == 2) {
            $user_count = self::getUserAllLotteriesCount($user_id, $lottery->id);
        }
        $count = $lottery->count - $user_count;
        return $count > 0 ? $count : 0;
    }

}